// lib/pages/today_home.dart
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import '../models/task.dart';
import '../theme/app_theme.dart';
import 'add_task_page.dart';
import 'pending_tasks_page.dart';
import 'task_detail_page.dart';

extension LinearGradientExtension on LinearGradient {
  LinearGradient withOpacity(double opacity) {
    return LinearGradient(
      begin: begin,
      end: end,
      colors: colors.map((color) => color.withOpacity(opacity)).toList(),
      stops: stops,
    );
  }
}


class TodayHomePage extends StatefulWidget {
  final List<Task> tasks;
  final Function(Task) onTaskUpdate;
  final Function(Task) onTaskDelete;

  const TodayHomePage({
    Key? key,
    required this.tasks,
    required this.onTaskUpdate,
    required this.onTaskDelete,
  }) : super(key: key);

  @override
  _TodayHomePageState createState() => _TodayHomePageState();
}

class _TodayHomePageState extends State<TodayHomePage> with SingleTickerProviderStateMixin, AppTheme {
  final _taskController = TextEditingController();
  final _noteController = TextEditingController();
  String _filterStatus = 'all'; // 'all', 'pending', 'completed', 'deleted'
  final String _userName = "Steven"; // 用户名
  bool _showCompletedTasks = true; // 是否显示已完成任务
  bool _showDeletedTasks = false; // 是否显示已删除任务
  
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;
  
  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1200),
    );
    
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.0, 0.6, curve: Curves.easeOut),
      ),
    );
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: const Interval(0.2, 0.8, curve: Curves.easeOutCubic),
      ),
    );
    
    _animationController.forward();
  }
  
  @override
  void dispose() {
    _animationController.dispose();
    _taskController.dispose();
    _noteController.dispose();
    super.dispose();
  }

  // 获取不同状态的任务数量
  int get _completedTaskCount => widget.tasks.where((task) => task.isCompleted).length;
  int get _pendingTaskCount => widget.tasks.where((task) => !task.isCompleted).length;
  int get _ongoingTaskCount => widget.tasks.where((task) => !task.isCompleted).length;
  int get _canceledTaskCount => 0; // 目前没有取消状态，设为0

  List<Task> get _todayTasks {
    final today = DateTime.now();
    final tasks = widget.tasks.where((task) {
      return task.time.year == today.year &&
          task.time.month == today.month &&
          task.time.day == today.day;
    }).toList();

    switch (_filterStatus) {
      case 'pending':
        return tasks.where((task) => !task.isCompleted && !task.isDeleted).toList();
      case 'completed':
        return tasks.where((task) => task.isCompleted && !task.isDeleted).toList();
      case 'deleted':
        return tasks.where((task) => task.isDeleted).toList();
      default: // 'all'
        return tasks.where((task) => !task.isDeleted).toList();
    }
  }

  void _deleteTask(Task task) {
    widget.onTaskDelete(task);
  }

  void _toggleTaskStatus(Task task) {
    setState(() {
      task.isCompleted = !task.isCompleted;
      widget.onTaskUpdate(task);
    });
  }

  // 打开任务详情
  void _openTaskDetail(Task task) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => TaskDetailPage(
          task: task,
          onTaskUpdate: (updatedTask) {
            setState(() {
              widget.onTaskUpdate(updatedTask);
            });
          },
          onTaskDelete: widget.onTaskDelete,
        ),
      ),
    );
  }

  // 添加新任务
  void _addNewTask() async {
    final newTask = await Navigator.push<Task>(
      context,
      MaterialPageRoute(
        builder: (context) => const AddTaskPage(),
      ),
    );
    
    if (newTask != null) {
      widget.onTaskUpdate(newTask);
    }
  }

  // 完成任务
  void _completeTask(Task task) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('完成任务'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('任务：${task.title}'),
            const SizedBox(height: 16),
            TextField(
              controller: _noteController,
              decoration: const InputDecoration(
                hintText: '添加备注（可选）',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              _noteController.clear();
              Navigator.pop(context);
            },
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              task.isCompleted = true;
              task.completedTime = DateTime.now();
              task.note = _noteController.text.isNotEmpty ? _noteController.text : null;
              widget.onTaskUpdate(task);
              _noteController.clear();
              Navigator.pop(context);
            },
            child: const Text('完成'),
          ),
        ],
      ),
    );
  }

  // 恢复任务
  void _restoreTask(Task task) {
    task.isDeleted = false;
    task.isCompleted = false;
    task.completedTime = null;
    task.note = null;
    widget.onTaskUpdate(task);
  }

  // 查看备注
  void _viewNote(Task task) {
    if (task.note != null) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('任务备注'),
          content: Text(task.note!),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('关闭'),
            ),
          ],
        ),
      );
    }
  }

  // 统计卡片
  Widget _buildStatisticsCards(List<Task> pendingTasks, List<Task> completedTasks, List<Task> deletedTasks) {
    return SlideTransition(
      position: _slideAnimation,
      child: FadeTransition(
        opacity: _fadeAnimation,
        child: Row(
      children: [
        Expanded(
          child: GestureDetector(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => PendingTasksPage(
                    tasks: widget.tasks,
                    onTaskUpdate: widget.onTaskUpdate,
                  ),
                ),
              );
            },
            child: _buildStatCard(
              '待完成',
              '${pendingTasks.length}',
                  AppTheme.warningColor,
                  Icons.schedule_rounded,
                  AppTheme.warningGradient,
            ),
          ),
        ),
            const SizedBox(width: AppTheme.paddingS),
        Expanded(
          child: _buildStatCard(
            '已完成',
            '${completedTasks.length}',
                AppTheme.successColor,
                Icons.check_circle_rounded,
                AppTheme.successGradient,
          ),
        ),
            const SizedBox(width: AppTheme.paddingS),
        Expanded(
          child: _buildStatCard(
            '已删除',
            '${deletedTasks.length}',
                AppTheme.errorColor,
                Icons.delete_rounded,
                LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [AppTheme.errorColor, Color(0xFFDC2626)],
                ),
          ),
        ),
      ],
        ),
      ),
    );
  }

  // 单个统计卡片
  Widget _buildStatCard(String title, String value, Color color, IconData icon, LinearGradient gradient) {
    return Container(
      padding: const EdgeInsets.all(AppTheme.paddingL),
      decoration: BoxDecoration(
        gradient: gradient.withOpacity(0.08),
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
        boxShadow: AppTheme.softShadow,
        border: Border.all(
          color: color.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: const EdgeInsets.all(AppTheme.paddingS),
            decoration: BoxDecoration(
              gradient: gradient,
              borderRadius: BorderRadius.circular(AppTheme.radiusM),
              boxShadow: [
                BoxShadow(
                  color: color.withOpacity(0.3),
                  blurRadius: 8,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Icon(
            icon,
              color: Colors.white,
            size: 24,
          ),
          ),
          const SizedBox(height: AppTheme.paddingM),
          Text(
            value,
            style: TextStyle(
              fontSize: AppTheme.fontSizeTitle,
              fontWeight: FontWeight.w700,
              color: color,
            ),
          ),
          const SizedBox(height: AppTheme.paddingXS),
          Text(
            title,
            style: const TextStyle(
              fontSize: AppTheme.fontSizeS,
              color: Colors.white,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  // 任务筛选按钮
  Widget _buildTaskFilter() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: [
          _buildFilterButton('全部', 'all'),
          const SizedBox(width: AppTheme.paddingM),
          _buildFilterButton('未完成', 'pending'),
          const SizedBox(width: AppTheme.paddingM),
          _buildFilterButton('已完成', 'completed'),
          const SizedBox(width: AppTheme.paddingM),
          _buildFilterButton('已删除', 'deleted'),
        ],
      ),
    );
  }

  // 单个筛选按钮
  Widget _buildFilterButton(String text, String status) {
    final isSelected = _filterStatus == status;
    return GestureDetector(
      onTap: () {
        setState(() {
          _filterStatus = status;
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: AppTheme.paddingL, vertical: AppTheme.paddingS),
        decoration: BoxDecoration(
          color: isSelected ? AppTheme.primaryColor : Colors.transparent,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: isSelected ? AppTheme.primaryColor : AppTheme.textSecondaryColor,
            width: 1,
          ),
        ),
        child: Text(
          text,
          style: TextStyle(
            color: isSelected ? Colors.white : AppTheme.textSecondaryColor,
            fontSize: AppTheme.fontSizeS,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  // 单个任务项
  Widget _buildTaskItem(
    Task task,
    Color color,
  ) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      margin: const EdgeInsets.only(bottom: AppTheme.paddingS),
      decoration: BoxDecoration(
        color: AppTheme.cardColor,
        borderRadius: BorderRadius.circular(AppTheme.radiusM),
        border: Border.all(
          color: color.withOpacity(0.15),
          width: 1,
        ),
        boxShadow: AppTheme.softShadow,
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(AppTheme.radiusM),
          onTap: () => _openTaskDetail(task),
          child: Padding(
            padding: const EdgeInsets.all(AppTheme.paddingL),
      child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
        children: [
                Row(
                  children: [
                    // 状态指示器
                    GestureDetector(
                      onTap: () => _toggleTaskStatus(task),
                      child: AnimatedContainer(
                        duration: const Duration(milliseconds: 200),
                        width: 24,
                        height: 24,
              decoration: BoxDecoration(
                          color: task.isCompleted ? color : Colors.transparent,
                shape: BoxShape.circle,
                          border: Border.all(
                color: color,
                            width: 2,
              ),
            ),
                        child: task.isCompleted
                            ? const Icon(
                                Icons.check_rounded,
                                color: Colors.white,
                                size: 16,
                              )
                            : null,
                      ),
                    ),
                    const SizedBox(width: AppTheme.paddingM),
                    // 任务标题
                    Expanded(
                      child: Text(
              task.title,
              style: TextStyle(
                          fontSize: AppTheme.fontSizeL,
                          fontWeight: FontWeight.w600,
                decoration: task.isCompleted ? TextDecoration.lineThrough : null,
                          color: task.isCompleted ? AppTheme.textLightColor : AppTheme.textPrimaryColor,
                        ),
              ),
            ),
                    // 操作按钮
                    if (!task.isDeleted) ...[
                      // 备注按钮（仅已完成且有备注的任务显示）
                      if (task.isCompleted && task.note != null)
                        Container(
                          margin: const EdgeInsets.only(left: AppTheme.paddingXS),
                          decoration: BoxDecoration(
                            color: AppTheme.infoColor.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(AppTheme.radiusS),
                          ),
                          child: IconButton(
                            icon: const Icon(Icons.note_rounded, size: 18),
                            onPressed: () => _viewNote(task),
                            color: AppTheme.infoColor,
                            padding: const EdgeInsets.all(AppTheme.paddingXS),
                            constraints: const BoxConstraints(
                              minWidth: 32,
                              minHeight: 32,
                            ),
                          ),
                        ),
                      // 删除按钮
                      Container(
                        margin: const EdgeInsets.only(left: AppTheme.paddingXS),
                        decoration: BoxDecoration(
                          color: AppTheme.errorColor.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(AppTheme.radiusS),
                        ),
                        child: IconButton(
                          icon: const Icon(Icons.delete_outline_rounded, size: 18),
                          onPressed: () => _showDeleteConfirmation(task),
                          color: AppTheme.errorColor,
                          padding: const EdgeInsets.all(AppTheme.paddingXS),
                          constraints: const BoxConstraints(
                            minWidth: 32,
                            minHeight: 32,
                          ),
                        ),
                      ),
                    ],
                  ],
          ),
                // 任务详情
                if (!task.isDeleted) ...[
                  const SizedBox(height: AppTheme.paddingS),
                  Row(
                    children: [
                      // 时间
                      Icon(
                        Icons.schedule_rounded,
                        size: 16,
                        color: AppTheme.textLightColor,
                      ),
                      const SizedBox(width: AppTheme.paddingXS),
                      Text(
                        DateFormat('HH:mm').format(task.time),
                        style: const TextStyle(
                          fontSize: AppTheme.fontSizeS,
                          color: AppTheme.textLightColor,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(width: AppTheme.paddingM),
                      // 地点
                      Icon(
                        Icons.location_on_rounded,
                        size: 16,
                        color: AppTheme.textLightColor,
                      ),
                      const SizedBox(width: AppTheme.paddingXS),
                      Text(
                        task.location,
                        style: const TextStyle(
                          fontSize: AppTheme.fontSizeS,
                          color: AppTheme.textLightColor,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: AppTheme.paddingS),
                  Row(
                    children: [
                      // 优先级
                      _buildPriorityTag(task.priority),
                      const SizedBox(width: AppTheme.paddingS),
                      // 分类
                      _buildCategoryTag(task.category),
                    ],
                  ),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 已完成区域
  Widget _buildCompletedSection(List<Task> completedTasks) {
    return DragTarget<Task>(
      onWillAccept: (task) => true,
      onAccept: (task) async {
        final confirmed = await showDialog<bool>(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('确认完成'),
            content: Text('确定要将任务"${task.title}"标记为已完成吗？'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () => Navigator.pop(context, true),
                child: const Text(
                  '完成',
                  style: TextStyle(color: Colors.green),
                ),
              ),
            ],
          ),
        ) ?? false;

        if (confirmed) {
          setState(() {
            task.isCompleted = true;
            task.isDeleted = false;
            widget.onTaskUpdate(task);
          });
        } else {
          setState(() {
            task.isCompleted = false;
            task.isDeleted = false;
            widget.onTaskUpdate(task);
          });
        }
      },
      builder: (context, candidateTasks, rejectedTasks) {
        return _buildTaskSection(
          '已完成',
          completedTasks,
          AppTheme.successColor,
        );
      },
    );
  }

  // 未完成区域
  Widget _buildPendingSection(List<Task> pendingTasks) {
    return DragTarget<Task>(
      onWillAccept: (task) => true,
      onAccept: (task) {
        setState(() {
          task.isCompleted = false;
          task.isDeleted = false;
          widget.onTaskUpdate(task);
        });
      },
      builder: (context, candidateTasks, rejectedTasks) {
        return _buildTaskSection(
          '未完成',
          pendingTasks,
          AppTheme.primaryColor,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final todayTasks = widget.tasks.where((task) {
      final taskDate = DateTime(task.time.year, task.time.month, task.time.day);
      return taskDate.isAtSameMomentAs(today);
    }).toList();

    final pendingTasks = todayTasks.where((task) => !task.isCompleted && !task.isDeleted).toList();
    final completedTasks = todayTasks.where((task) => task.isCompleted && !task.isDeleted).toList();
    final deletedTasks = todayTasks.where((task) => task.isDeleted).toList();

    final totalTasks = pendingTasks.length + completedTasks.length; // 只计算未删除的任务
    final completionRate = totalTasks > 0 ? completedTasks.length / totalTasks : 0.0;

    return Scaffold(
      backgroundColor: AppTheme.scaffoldColor,
      body: SafeArea(
        child: Column(
              children: [
                // 顶部卡片
            SlideTransition(
              position: _slideAnimation,
              child: FadeTransition(
                opacity: _fadeAnimation,
                child: Container(
                  margin: const EdgeInsets.all(AppTheme.paddingM),
                  padding: const EdgeInsets.all(AppTheme.paddingXL),
                  decoration: BoxDecoration(
                    gradient: AppTheme.primaryGradient,
                    borderRadius: BorderRadius.circular(AppTheme.radiusXL),
                    boxShadow: AppTheme.mediumShadow,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '早安，$_userName',
                                style: const TextStyle(
                                  fontSize: AppTheme.fontSizeL,
                                  color: Colors.white70,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              const SizedBox(height: AppTheme.paddingXS),
                              Text(
                                DateFormat('yyyy年MM月dd日').format(now),
                                style: const TextStyle(
                                  fontSize: AppTheme.fontSizeLarge,
                                  fontWeight: FontWeight.w700,
                                  color: Colors.white,
                                ),
                              ),
                              Text(
                                DateFormat('EEEE').format(now),
                                style: const TextStyle(
                                  fontSize: AppTheme.fontSizeL,
                                  color: Colors.white70,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              Container(
                                decoration: BoxDecoration(
                                  color: Colors.white.withOpacity(0.2),
                                  borderRadius: BorderRadius.circular(AppTheme.radiusM),
                                ),
                                child: IconButton(
                                  icon: const Icon(Icons.delete_sweep_rounded),
                                onPressed: () {
                                  setState(() {
                                    _showDeletedTasks = true;
                                  });
                                },
                                  color: Colors.white,
                                tooltip: '查看已删除任务',
                              ),
                              ),
                              const SizedBox(width: AppTheme.paddingS),
                              Container(
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(AppTheme.radiusM),
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.black.withOpacity(0.1),
                                      blurRadius: 8,
                                      offset: const Offset(0, 4),
                                    ),
                                  ],
                                ),
                                child: IconButton(
                                  icon: const Icon(Icons.add_rounded),
                                onPressed: _addNewTask,
                                  color: AppTheme.primaryColor,
                                  iconSize: 28,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      const SizedBox(height: 20),
                      // 进度条
                      Container(
                        padding: const EdgeInsets.all(AppTheme.paddingL),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.15),
                          borderRadius: BorderRadius.circular(AppTheme.radiusL),
                          border: Border.all(
                            color: Colors.white.withOpacity(0.2),
                            width: 1,
                          ),
                        ),
                        child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                                const Text(
                                '今日进度',
                                style: TextStyle(
                                    fontSize: AppTheme.fontSizeL,
                                    color: Colors.white,
                                    fontWeight: FontWeight.w600,
                                ),
                              ),
                              Text(
                                '${(completionRate * 100).toStringAsFixed(0)}%',
                                style: const TextStyle(
                                    fontSize: AppTheme.fontSizeXXL,
                                    fontWeight: FontWeight.w700,
                                    color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                            const SizedBox(height: AppTheme.paddingM),
                          ClipRRect(
                              borderRadius: BorderRadius.circular(AppTheme.radiusM),
                            child: LinearProgressIndicator(
                              value: completionRate,
                                backgroundColor: Colors.white.withOpacity(0.3),
                                valueColor: const AlwaysStoppedAnimation<Color>(Colors.white),
                              minHeight: 8,
                            ),
                          ),
                            const SizedBox(height: AppTheme.paddingS),
                          Text(
                            '已完成 ${completedTasks.length} 项，共 $totalTasks 项任务',
                              style: const TextStyle(
                                fontSize: AppTheme.fontSizeM,
                                color: Colors.white70,
                                fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                        ),
                      ),
                      const SizedBox(height: 20),
                      // 统计卡片
                      _buildStatisticsCards(pendingTasks, completedTasks, deletedTasks),
                    ],
                  ),
                ),
                  ),
                ),

                // 任务区域
                Expanded(
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      // 未完成区域
                      Expanded(
                        child: _buildPendingSection(pendingTasks),
                      ),
                      // 已完成区域
                      Expanded(
                        child: _buildCompletedSection(completedTasks),
                      ),
                    ],
                  ),
                ),
              ],
            ),
      ),
    );
  }

  // 任务区域构建
  Widget _buildTaskSection(
    String title,
    List<Task> tasks,
    Color color,
  ) {
    return Container(
      margin: const EdgeInsets.all(AppTheme.paddingS),
      decoration: AppTheme.elevatedCardDecoration,
      child: Column(
        children: [
          // 标题栏
          Container(
            padding: const EdgeInsets.all(AppTheme.paddingL),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [color.withOpacity(0.1), color.withOpacity(0.05)],
              ),
              borderRadius: const BorderRadius.vertical(
                top: Radius.circular(AppTheme.radiusL),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontSize: AppTheme.fontSizeXL,
                    fontWeight: FontWeight.w700,
                    color: color,
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: AppTheme.paddingM,
                    vertical: AppTheme.paddingXS,
                  ),
                  decoration: BoxDecoration(
                    color: color.withOpacity(0.15),
                    borderRadius: BorderRadius.circular(AppTheme.radiusXXL),
                    border: Border.all(
                      color: color.withOpacity(0.3),
                      width: 1,
                    ),
                  ),
                  child: Text(
                    '${tasks.length}',
                    style: TextStyle(
                      fontSize: AppTheme.fontSizeM,
                      color: color,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 任务列表
          Expanded(
            child: tasks.isEmpty
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          title == '未完成' ? Icons.task_alt_rounded : Icons.check_circle_outline_rounded,
                          size: 48,
                          color: AppTheme.textLightColor,
                        ),
                        const SizedBox(height: AppTheme.paddingM),
                        Text(
                          title == '未完成' ? '暂无待办任务' : '暂无已完成任务',
                          style: const TextStyle(
                            fontSize: AppTheme.fontSizeM,
                            color: AppTheme.textLightColor,
                            fontWeight: FontWeight.w500,
                          ),
                      ),
                      ],
                    ),
                  )
                : ListView.builder(
                    padding: const EdgeInsets.all(AppTheme.paddingS),
                    itemCount: tasks.length,
                    itemBuilder: (context, index) {
                      final task = tasks[index];
                      return Draggable<Task>(
                        key: ValueKey(task.id),
                        data: task,
                        feedback: Material(
                          elevation: 8,
                          borderRadius: BorderRadius.circular(AppTheme.radiusM),
                          child: Container(
                            width: MediaQuery.of(context).size.width / 3 - 32,
                            padding: const EdgeInsets.all(AppTheme.paddingL),
                            decoration: BoxDecoration(
                              color: AppTheme.cardColor,
                              borderRadius: BorderRadius.circular(AppTheme.radiusM),
                              boxShadow: AppTheme.strongShadow,
                            ),
                            child: Text(
                              task.title,
                              style: const TextStyle(
                                fontSize: AppTheme.fontSizeM,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ),
                        childWhenDragging: Container(
                          margin: const EdgeInsets.only(bottom: AppTheme.paddingS),
                          height: 80,
                          decoration: BoxDecoration(
                            color: AppTheme.surfaceColor,
                            borderRadius: BorderRadius.circular(AppTheme.radiusM),
                            border: Border.all(
                              color: AppTheme.textLightColor,
                              width: 2,
                              strokeAlign: BorderSide.strokeAlignInside,
                            ),
                          ),
                          child: const Center(
                            child: Icon(
                              Icons.drag_indicator_rounded,
                              color: AppTheme.textLightColor,
                            ),
                          ),
                        ),
                        child: _buildTaskItem(task, color),
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }

  // 显示删除确认对话框
  void _showDeleteConfirmation(Task task) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(AppTheme.radiusL),
        ),
        title: const Text(
          '确认删除',
          style: TextStyle(
            fontSize: AppTheme.fontSizeXL,
            fontWeight: FontWeight.w600,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        content: Text(
          '确定要删除任务"${task.title}"吗？',
          style: const TextStyle(
            fontSize: AppTheme.fontSizeM,
            color: AppTheme.textSecondaryColor,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            style: TextButton.styleFrom(
              padding: const EdgeInsets.symmetric(
                horizontal: AppTheme.paddingL,
                vertical: AppTheme.paddingM,
              ),
            ),
            child: const Text(
              '取消',
              style: TextStyle(
                color: AppTheme.textSecondaryColor,
                fontSize: AppTheme.fontSizeM,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              setState(() {
                task.isDeleted = true;
                widget.onTaskUpdate(task);
              });
              Navigator.pop(context);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppTheme.errorColor,
              padding: const EdgeInsets.symmetric(
                horizontal: AppTheme.paddingL,
                vertical: AppTheme.paddingM,
              ),
            ),
            child: const Text(
              '删除',
              style: TextStyle(
                color: Colors.white,
                fontSize: AppTheme.fontSizeM,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建优先级标签
  Widget _buildPriorityTag(int priority) {
    Color color;
    String text;
    IconData icon;
    
    switch (priority) {
      case 1:
        color = Colors.green;
        text = '低';
        icon = Icons.keyboard_arrow_down;
        break;
      case 2:
        color = Colors.orange;
        text = '中';
        icon = Icons.remove;
        break;
      case 3:
        color = Colors.red;
        text = '高';
        icon = Icons.keyboard_arrow_up;
        break;
      default:
        color = Colors.grey;
        text = '中';
        icon = Icons.remove;
    }

    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: AppTheme.paddingS,
        vertical: 2,
      ),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(AppTheme.radiusS),
        border: Border.all(
          color: color.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 12,
            color: color,
          ),
          const SizedBox(width: 2),
          Text(
            text,
            style: TextStyle(
              fontSize: AppTheme.fontSizeXS,
              color: color,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  // 构建分类标签
  Widget _buildCategoryTag(String category) {
    Color color;
    IconData icon;
    
    switch (category) {
      case 'Personal':
        color = Colors.blue;
        icon = Icons.person;
        break;
      case 'Work':
        color = Colors.purple;
        icon = Icons.work;
        break;
      case 'Private':
        color = Colors.teal;
        icon = Icons.lock;
        break;
      case 'Meeting':
        color = Colors.orange;
        icon = Icons.people;
        break;
      case 'Events':
        color = Colors.pink;
        icon = Icons.event;
        break;
      default:
        color = Colors.grey;
        icon = Icons.label;
    }

    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: AppTheme.paddingS,
        vertical: 2,
      ),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(AppTheme.radiusS),
        border: Border.all(
          color: color.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 12,
            color: color,
          ),
          const SizedBox(width: 2),
          Text(
            category,
            style: TextStyle(
              fontSize: AppTheme.fontSizeXS,
              color: color,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }
}